<?php
namespace App\Ext\SMS;

use Log;

class SayenService
{
    private $account;
    private $password;
    private $product;
    private $extno;
    private $api;

    public function config($param)
    {
        # 帐号
        $this->account = $param['user'];
        # 密码
        $this->password = $param['password'];
        # 是否需要状态报告，需要true，不需要false
        $this->needstatus = 'false';
        # 产品ID 不需要填写
        $this->product = '';
        # 扩展码 不用填写
        $this->extno = '';
        # 短信发送接口地址
        $this->api['send'] = 'http://120.26.69.248/msg/HttpBatchSendSM';
    }

    public function send($phone, $msg)
    {
        $data = array();
        # 短信内容需要用urlencode编码下
        $data['msg'] = $msg;
        # 手机号码， 多个用英文状态下的 , 隔开
        $data['mobile'] = $phone;
        $data['account'] = $this->account;
        $data['pswd'] = $this->password;
        $data['product'] = $this->product;
        $data['needstatus'] = $this->needstatus;
        $data['extno'] = $this->extno;
        # 记录请求报文
        // Log::info('SMS request', ['param' => $phone]);
        # 拼接请求字符串
        $str = '';
        foreach ($data as $k => $v)
        {
            $str .= $k . '=' . urlencode($v) . '&';
        }
        # 发送请求
        $data = substr($str, 0, -1);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_URL, $this->api['send']);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        # 如果需要将结果直接返回到变量里，那加上这句
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        # 记录请求返回报文
        // Log::info('SMS response', ['data' => $result]);
        # 自己解析$result的字符串并实现自己的逻辑
        $result = explode(',', $result);
        if ($result[1] == '0') {
            return true;
        }
        return false;
    }
}